import time,sys,json
from math import isnan
from threading import Thread
from ctp.thosttraderapi import THOST_FTDC_D_Buy,THOST_FTDC_D_Sell,THOST_FTDC_OF_Open,THOST_FTDC_OF_Close,THOST_FTDC_OF_CloseToday
from ctp.ctpApi import CTPapi,orderfield,signalHandle
from mainUI_ui import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QApplication,QTableWidgetItem,QPushButton,QButtonGroup#,QHeaderView,QPushButton,QWidget,QAbstractItemView
from PyQt5.QtCore import Qt,QObject,pyqtSignal,QEvent#,QStringListModel,QTextStream,pyqtSignal,QSize
from PyQt5.QtGui import QIcon,QFont,QColor

class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self,signalHandle,CTPapi) -> None:
        super().__init__()   #QMainWindow的初始化
        self.setupUi(self)   #把Qmainwindow放进UI类，作为背景窗口，然后添加控件
        self.setWindowTitle('自动挂平')
        self.setWindowIcon(QIcon('play.png'))
        self.CTPapi,self.signalHandle=CTPapi,signalHandle
        self.isRunning=True
        self.signalHandle.profitIntSignal.emit(2)
        self.pushButton.setIcon(QIcon('pause.png'))
        self.radioButton_2.setChecked(True)
        # self.pushButton.setScaledContents(True)
        self.pushButton.clicked.connect(self.toggleIcon)
        self.buttonGroup = QButtonGroup(self)
        self.buttonGroup.addButton(self.radioButton, 1)
        self.buttonGroup.addButton(self.radioButton_2, 2)
        self.buttonGroup.addButton(self.radioButton_3, 3)
        self.buttonGroup.addButton(self.radioButton_4, 4)
        self.buttonGroup.buttonClicked.connect(self.radioClick)
        
        #CTP接口  

        Thread(target=self.Join).start()
    def toggleIcon(self):
        # 判断当前图标，并切换到另一个图标
        self.isRunning=not self.isRunning
        self.signalHandle.isRunningSignal.emit(self.isRunning)
        
        self.pushButton.setIcon(QIcon('pause.png')) if self.isRunning else self.pushButton.setIcon(QIcon('play.png'))
        
            
    def radioClick(self,button):
        i = int(button.text())
        self.signalHandle.profitIntSignal.emit(i)
        font = QFont()
        font.setFamily("Arial")
        for but in [self.radioButton,self.radioButton_2,self.radioButton_3,self.radioButton_4]:
            font.setPointSize(28)
            font.setBold(False)
            but.setFont(font)
            
        font.setPointSize(36)
        font.setBold(True)
        button.setFont(font)
    def Join(self):
        self.CTPapi.Init()
        self.CTPapi.Join()
    def closeEvent(self, a0):
        self.CTPapi.Release()
        print('销毁线程')
        sys.exit(0)
if __name__=="__main__":
    app = QApplication(sys.argv)
    mWindow=MainWindow(signalHandle,CTPapi)
    mWindow.show()
    sys.exit(app.exec())